package com.bootcamp.mall.controller.mall;

/**
 * @program: mall
 * @author: Keyu Li
 * @create: 2021-11-12 21:41
 **/

import com.bootcamp.mall.model.Result;
import com.bootcamp.mall.model.bo.order.AddOrderBO;
import com.bootcamp.mall.model.bo.order.ChangeOrderBO;
import com.bootcamp.mall.model.bo.order.CommentBO;
import com.bootcamp.mall.model.bo.order.SettleAccountBO;
import com.bootcamp.mall.model.vo.order.GetOrderByStateVO;
import com.bootcamp.mall.service.order.OrderService;
import com.bootcamp.mall.service.order.OrderServiceImpl;
import com.bootcamp.mall.utils.JSONUtil;
import com.bootcamp.mall.utils.StringUtil;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet(name = "MallOrderServlet", value = "/api/mall/*")
public class MallOrderServlet extends HttpServlet {

    Gson gson = new Gson();
    OrderService orderService = new OrderServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String op = request.getRequestURI().replace("/api/mall/order/", "");
        if ("deleteOrder".equals(op)) {
            opDeleteOrder(request, response);
        } else if ("getOrderByState".equals(op)) {
            opGetOrderByState(request, response);
        } else if ("confirmReceive".equals(op)){
            opConfirmReceive(request,response);
        } else if ("pay".equals(op)){
            opPay(request, response);
        }
    }


    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String op = request.getRequestURI().replace("/api/mall/order/", "");
        if ("addOrder".equals(op)) {
            opAddOrder(request, response);
        } else if ("settleAccounts".equals(op)){
            opSettleAccounts(request, response);
        } else if ("sendComment".equals(op)){
            opSendComment(request, response);
        }
    }

    private void opSendComment(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 接收字符串并解析为对象四连
        PrintWriter writer = response.getWriter();
        // json解析四联：获取字符串，判断不为空，获取对象，捕获异常判断参数合法
        String jsonContent = JSONUtil.parseContent(request);
        // 合法性
        if (StringUtil.isEmpty(jsonContent)) {
            writer.println(gson.toJson(Result.error("前端异常！")));
            return;
        }
        // jsonContent 解析为 bo
        // json转换为AddGoodsBO对象
        JsonObject asJsonObject = new JsonParser().parse(jsonContent).getAsJsonObject();
        try {
            CommentBO commentBO = gson.fromJson(asJsonObject, CommentBO.class);
            // 一般是肯定能够正常返回的
            Integer code = orderService.sendComment(commentBO);
            if (code == 0) {
                writer.println(gson.toJson(Result.ok()));
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
            writer.println(gson.toJson(Result.error("请求参数异常！")));
            return;
        }
        writer.println(gson.toJson(Result.error("服务器异常！")));
    }

    private void opPay(HttpServletRequest request, HttpServletResponse response) throws IOException {
        PrintWriter writer = response.getWriter();
        // 从url中获取参数
        int id;
        try {
            id = Integer.parseInt(request.getParameter("id"));
        } catch (NumberFormatException e) {
            writer.println(gson.toJson(Result.error("前端参数异常")));
            return;
        }
        Integer code = orderService.changeState(id);
        if (code == 0) {
            writer.println(gson.toJson(Result.ok()));
            return;
        }
        writer.println(gson.toJson(Result.error("服务器异常！")));
    }

    private void opConfirmReceive(HttpServletRequest request, HttpServletResponse response) throws IOException {
        PrintWriter writer = response.getWriter();
        // 从url中获取参数
        int id;
        try {
            id = Integer.parseInt(request.getParameter("id"));
        } catch (NumberFormatException e) {
            writer.println(gson.toJson(Result.error("前端参数异常")));
            return;
        }
        Integer code = orderService.changeState(id);
        if (code == 0) {
            writer.println(gson.toJson(Result.ok()));
            return;
        }
        writer.println(gson.toJson(Result.error("服务器异常！")));
    }


    private void opSettleAccounts(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 接收字符串并解析为对象四连
        PrintWriter writer = response.getWriter();
        // json解析四联：获取字符串，判断不为空，获取对象，捕获异常判断参数合法
        String jsonContent = JSONUtil.parseContent(request);
        // 合法性
        if (StringUtil.isEmpty(jsonContent)) {
            writer.println(gson.toJson(Result.error("前端异常！")));
            return;
        }
        // jsonContent 解析为 bo
        // json转换为AddGoodsBO对象
        JsonObject asJsonObject = new JsonParser().parse(jsonContent).getAsJsonObject();
        try {
            SettleAccountBO settleBO = gson.fromJson(asJsonObject, SettleAccountBO.class);
            // 一般是肯定能够正常返回的
            Integer code = orderService.settleAccount(settleBO);
            if (code == 0) {
                writer.println(gson.toJson(Result.ok()));
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
            writer.println(gson.toJson(Result.error("请求参数异常！")));
            return;
        }
        writer.println(gson.toJson(Result.error("服务器异常！")));
    }


    private void opGetOrderByState(HttpServletRequest request, HttpServletResponse response) throws IOException {
        PrintWriter writer = response.getWriter();
        // 从url中获取对象
        String nickname = request.getParameter("token");
        int state;
        try {
            state = Integer.parseInt(request.getParameter("state"));
            if (state < -1 || state > 3)
                throw new Exception("state状态错误！");
        } catch (Exception e) {
            e.printStackTrace();
            writer.println(gson.toJson(Result.error("参数异常！")));
            return;
        }
        // 传入service，返回 vo list
        List<GetOrderByStateVO> getOrderByStateVOS = orderService.getOrderByState(state, nickname);
        // 不管返回是否为null，都是ok
        writer.println(gson.toJson(Result.ok(getOrderByStateVOS)));

    }


    private void opDeleteOrder(HttpServletRequest request, HttpServletResponse response) throws IOException {
        PrintWriter writer = response.getWriter();
        // 从url中获取参数
        int id;
        try {
            id = Integer.parseInt(request.getParameter("id"));
        } catch (NumberFormatException e) {
            writer.println(gson.toJson(Result.error("前端参数异常")));
            return;
        }
        Integer code = orderService.deleteOrder(id);
        if (code == 0) {
            writer.println(gson.toJson(Result.ok()));
            return;
        }
        writer.println(gson.toJson(Result.error("服务器异常！")));
    }


    private void opAddOrder(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 接收字符串并解析为对象四连
        PrintWriter writer = response.getWriter();
        // json解析四联：获取字符串，判断不为空，获取对象，捕获异常判断参数合法
        String jsonContent = JSONUtil.parseContent(request);
        // 合法性
        if (StringUtil.isEmpty(jsonContent)) {
            writer.println(gson.toJson(Result.error("前端异常！")));
            return;
        }
        // jsonContent 解析为 bo
        // json转换为AddGoodsBO对象
        JsonObject asJsonObject = new JsonParser().parse(jsonContent).getAsJsonObject();
        try {
            AddOrderBO addOrderBO = gson.fromJson(asJsonObject, AddOrderBO.class);
            // 一般是肯定能够正常返回的
            Integer code = orderService.addOrder(addOrderBO);
            if (code == 0) {
                writer.println(gson.toJson(Result.ok()));
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
            writer.println(gson.toJson(Result.error("请求参数异常！")));
            return;
        }
        writer.println(gson.toJson(Result.error("服务器异常！")));
    }
}
